package com.xiyuan.smartutils;

import java.util.HashMap;
import java.util.Map;

/**
 * the description for class
 *
 * @author xiyuan-lgz 2022-10-18 @version v1.0.0 新建与整理
 */
public class Colors {
    /**
     * 色差范围0~255
     */
    private static final int COLOR_RANGE = 210;
    private static final Map<Integer, String> MAP = new HashMap<Integer, String>();
    
    static {
        int a = 10;
        MAP.put(a++, "A");
        MAP.put(a++, "B");
        MAP.put(a++, "C");
        MAP.put(a++, "D");
        MAP.put(a++, "E");
        MAP.put(a++, "F");
    }
    
    private static String getValue(int key) {
        return MAP.containsKey(key) ? MAP.get(key) : String.valueOf(key);
    }
    
    public static class Rgb {
        public int r;
        public int g;
        public int b;
        
        public Rgb(int r, int g, int b) {
            super();
            this.r = r;
            this.g = g;
            this.b = b;
        }
        
    }
    
    /**
     * hex颜色值转换成rgb
     */
    public static Rgb toRgb(String hexColor) throws Exception {
        int z = 0;
        int color = Integer.decode(hexColor);
        int r = (color >> 16) & 0xFF;
        int g = (color >> 8) & 0xFF;
        int b = (color >> z) & 0xFF;
        return new Rgb(r, g, b);
    }
    
    /**
     * rgb 转换Hex
     */
    public static String toHex(int r, int g, int b) {
        String badComponentString = "";
        if (r < 0 || r > 255) {badComponentString = badComponentString + " Red";}
        if (g < 0 || g > 255) {badComponentString = badComponentString + " Green";}
        if (b < 0 || b > 255) {badComponentString = badComponentString + " Blue";}
        if (!badComponentString.isEmpty()) {
            throw new IllegalArgumentException("Color parameter outside of expected range:" + badComponentString);
        }
        
        StringBuilder sb = new StringBuilder("0x");
        sb.append(getValue(r / 16));
        sb.append(getValue(r % 16));
        
        sb.append(getValue(g / 16));
        sb.append(getValue(g % 16));
        
        sb.append(getValue(b / 16));
        sb.append(getValue(b % 16));
        
        return sb.toString();
    }
    
    /***
     * 判断是背景还是内容
     *
     * @param color     颜色值
     * @return true|false
     */
    public static boolean colorInRange(int color) {
        int red = (color & 0xff0000) >> 16;// 获取color(RGB)中R位
        int green = (color & 0x00ff00) >> 8;// 获取color(RGB)中G位
        int blue = (color & 0x0000ff);// 获取color(RGB)中B位
        // 通过RGB三分量来判断当前颜色是否在指定的颜色区间内
        return red >= COLOR_RANGE && green >= COLOR_RANGE && blue >= COLOR_RANGE;
    }
    
}
